package project.innovation.mooddiagnosis.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import project.innovation.mooddiagnosis.config.AppConfig;
import project.innovation.mooddiagnosis.service.UserService;
import org.springframework.http.HttpEntity;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AppConfig appConfig;

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    public String getOpenIdFromWX(String code) throws IOException {
        logger.info("code: {}", code);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url += "?appid=" + appId;//自己的appid
        url += "&secret=" + appSecret;//自己的appSecret
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
//        url += "&connect_redirect=1";

//        String res = null;
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//        // DefaultHttpClient();
//        HttpGet httpget = new HttpGet(url);
//        CloseableHttpResponse response = null;
//
//
//        RequestConfig requestConfig = RequestConfig.custom()          // 设置连接超时时间(单位毫秒)
//                .setConnectTimeout(5000)                    // 设置请求超时时间(单位毫秒)
//                .setConnectionRequestTimeout(5000)             // socket读写超时时间(单位毫秒)
//                .setSocketTimeout(5000)                    // 设置是否允许重定向(默认为true)
//                .setRedirectsEnabled(false).build();           // 将上面的配置信息 运用到这个Get请求里
//        httpget.setConfig(requestConfig);                         // 由客户端执行(发送)Get请求
//        response = httpClient.execute(httpget);                   // 从响应模型中获取响应实体
//        org.apache.http.HttpEntity responseEntity = response.getEntity();
//        System.out.println("响应状态为:" + response.getStatusLine());
//
//        if (responseEntity != null) {
//            res = EntityUtils.toString(responseEntity);
//            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
//            System.out.println("响应内容为:" + res);
//        }
//        // 释放资源
//        if (httpClient != null) {
//            httpClient.close();
//        }
//        if (response != null) {
//            response.close();
//        }
//        com.alibaba.fastjson.JSONObject jo = JSON.parseObject(res);
//        String openid = jo.getString("openid");
//        System.out.println("openid" + openid);
//        return openid;

        ClientHttpRequestFactory clientHttpRequestFactory = appConfig.clientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

        String forObject = restTemplate.getForObject(url, String.class);
        try {
            Map map = JSON.parseObject(forObject, Map.class);
            String openid = null;
            assert map != null;
            if (map.containsKey("openid")) {
                openid = map.get("openid").toString();
            } else {
                String forError = getErrorMessage(restTemplate, map);
                logger.error("https://api.weixin.qq.com/sns/jscode2session error: {}", forError);
            }
            return openid;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String extractRid(String message) {
        String[] parts = message.split(", rid: ");
        return parts.length > 1 ? parts[1] : null;
    }

    private String getAccessToken(RestTemplate restTemplate) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String ret = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(ret);
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }

    private String getStablAeccessToken() {
        String access_token_url = "https://api.weixin.qq.com/cgi-bin/stable_token?grant_type=client_credential";
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头 (可选)
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json"); // 如果需要设置其他头，可以添加

        // 构造请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        access_token_url += "&appid=" + appId + "&secret=" + appSecret;

        // 发送 POST 请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(access_token_url,
                HttpMethod.POST, requestEntity, String.class);

        // 获取响应内容
        String access_token = responseEntity.getBody();
        return access_token;
    }

    private String getErrorMessage(RestTemplate restTemplate, Map map) throws JsonProcessingException {
        String error_url = "https://api.weixin.qq.com/cgi-bin/openapi/rid/get?access_token=" + getAccessToken(restTemplate);
        String errorMessage = map.get("errmsg").toString();

        String rid = extractRid(errorMessage);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        Map<String,String> params = new HashMap<>();
        params.put("rid", rid);

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonRequestBody = objectMapper.writeValueAsString(params);

        HttpEntity<String> request = new HttpEntity<>(jsonRequestBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( error_url, request , String.class );
        return response.getBody();
    }
}
